package tools

import (
	"errors"
	"fmt"
	"github.com/xuri/excelize/v2"
	"os"
	"strings"
	"time"
)

func slice2ArrayString(data []string) string {
	s := "    ["
	n := len(data)
	for i, v := range data {
		v = strings.ReplaceAll(v, "\n", "")
		if n-1 == i {
			s += fmt.Sprintf(`"%s"`, v)
		} else {
			s += fmt.Sprintf(`"%s",`, v)
		}
	}
	s += "],\n"
	return s
}

func Xls2js(args []string) (err error) {
	// 检查路径是否存在
	fileName := args[1]
	if !PathExists(fileName) {
		return errors.New("指定文件不存在")
	}

	// 打开excel文件
	f, err := excelize.OpenFile(fileName)
	if err != nil {
		return err
	}
	defer f.Close()

	sheets := f.GetSheetList()
	if len(sheets) == 0 {
		fmt.Println("表内没有数据!")
		return nil
	}

	rows, err := f.GetRows(sheets[0])
	if err != nil {
		return err
	}

	//  输出文件生成路径
	outFile := PathReplaceFile(fmt.Sprintf("%s-%s.js", args[0], time.Now().Format("20060102150405")), fileName)
	file, err := os.Create(outFile)
	if err != nil {
		return err
	}
	defer file.Close()

	// 写入头
	if _, err = file.Write([]byte("let data = [\n")); err != nil {
		return err
	}

	for _, row := range rows {
		// 遍历数据写每一行
		if _, err = file.Write([]byte(slice2ArrayString(row))); err != nil {
			return err
		}
	}

	// 写入尾
	if _, err = file.Write([]byte("]\n")); err != nil {
		return err
	}

	fmt.Println("文件已写入:", outFile)
	return nil
}

func ExcelTool() *Option {
	return &Option{"xls2js", Xls2js, `xls2array <指定文件路径> excel数据转为js数组 eg. xls2js test.xlsx`}
}
